package com.pearl.study.client.demo.lua;

import io.lettuce.core.RedisClient;
import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author TD
 * @version 1.0
 * @date 2024/7/25
 */
public class LuaLimitTest {

    public static void main(String[] args) {
        // 创建客户端
        RedisClient redisClient = RedisClient.create("redis://:123456@127.0.0.1:6379/0");
        // 获取连接
        try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
            // 执行命令
            RedisCommands<String, String> sync = connection.sync();
            // 获取脚本流
            byte[] lua = RedisLockUtils.getResourceAsByteArray("limit.lua");
            // 执行脚本
            boolean eval = sync.eval(lua, ScriptOutputType.BOOLEAN, new String[]{"127.0.0.1"}, "1");

            // 结果判断
            if (!eval) {
                System.out.println("当前访问过于频繁，请稍后重试");
            } else {
                System.out.println("允许访问");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            redisClient.shutdown();
        }
    }


}
